package com.github.hgkmail.hello.leetcode101.collection.array;

//矩阵旋转，行变成列，公式：(row, col) -> (col, n-1-row)
//原地旋转，需要4个一组进行旋转
public class LC48RotateImage {

    //辅助数组
    public void rotate1(int[][] matrix) {
        int n=matrix.length;
        if (n<=0) {
            return;
        }
        int[][] temp = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                temp[j][n-1-i] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = temp[i][j];
            }
        }
    }

    // 原地算法，4个一组进行旋转
    // (i,j)              (j, n-1-i)
    // (n-1-j, i)         (n-1-i, n-1-j)
    //循环控制分奇偶进行讨论：n为偶数时,i<n/2，j<n/2；n为奇数时，i<(n+1)/2，j<n/2
    //通过舍弃小数，统一为：i<(n+1)/2，j<n/2
    public void rotate2(int[][] matrix) {
        int n=matrix.length;
        if (n<=0) {
            return;
        }
        int temp;
        int row=(n+1)/2;
        int col=n/2;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n-1-j][i];
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
                matrix[j][n-1-i] = temp;
            }
        }
    }

    public static void main(String[] args) {

    }
}
